package com.boarsoft.boar.batch.service;

import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.batch.biz.BatchSummaryBiz;
import com.boarsoft.boar.batch.entity.BatchExecution;
import com.boarsoft.boar.batch.entity.BatchSummary;
import com.boarsoft.common.util.DateUtil;
import com.boarsoft.common.util.StringUtil;
import com.boarsoft.hibernate.dao.SimpleDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class BatchSummaryServiceImpl implements BatchSummaryService {

    private static final Logger log = LoggerFactory.getLogger(BatchSummaryServiceImpl.class);

    @Autowired
    private BatchSummaryBiz batchSummaryBiz;
    @Autowired
    private SimpleDao simpleDao;

    /**
     * 任务（订单）执行概要监息上报接口
     *
     * @param batchId    任务ID（订单号）
     * @param totalCount 总条数
     * @param succCount  成功条数
     * @param errCount   处理失败条数 （可选参数）
     * @param skipCount  跳过处理条数 （可选参数）
     * @param summary    执行概要监息 （可选参数）
     * @return
     */
    @Override
    public ReplyInfo<Object> summaryReport(String batchId, Integer totalCount, Integer succCount, Integer errCount, Integer skipCount, String summary) {
        log.info("received batchId:{} summaryReport, totalCount:{}, succCount:{}, errCount:{}, skipCount:{}",
                batchId, totalCount, succCount, errCount, skipCount);
        if (StringUtil.isEmpty(batchId)) {
            return ReplyInfo.error("batchId不允许为空");
        }
        BatchSummary o = batchSummaryBiz.findByBatchId(batchId);
        if(o == null || o.getId() == null){
            o = new BatchSummary();
        }
        o.setBatchId(batchId);
        o.setTotalCount(getNotNull(totalCount));
        o.setSuccCount(getNotNull(succCount));
        o.setErrCount(getNotNull(errCount));
        o.setSkipCount(getNotNull(skipCount));
        o.setSummary(summary);
        o.setLastTime(DateUtil.yyyyMMddHHmmss());
        batchSummaryBiz.save(o);
        return ReplyInfo.SUCCESS;
    }

    @Override
    public ReplyInfo<Object> get(String batchId, String no) {
        if (StringUtil.isEmpty(batchId)) {
            return ReplyInfo.error("batchId不允许为空");
        }
        ReplyInfo<Object> out = new ReplyInfo<Object>();
        String hql = " from BatchSummary where 1=1 and vBatchId = '" + batchId + "' and tNo ='" + no + "'";
        BatchSummary b = simpleDao.find(hql, BatchSummary.class);
        out.setData(b);
        return out;
    }

    /**
     * 值为null时统一转换成-1
     * @param value
     * @return
     */
    private int getNotNull(Integer value) {
        int defaultValue = -1;
        return value == null ? defaultValue : value;
    }
}
